﻿using UnityEngine.EventSystems;

namespace UnityEngine.UI
{

	public enum InlineAlignment
	{
		Center = 0,
		Buttom = 1,
	}
	//pube
	[RequireComponent(typeof(Text))]
	[ExecuteInEditMode]

	public class TextInline : UIBehaviour
	{
		[SerializeField] private InlineAlignment mLineAlignment = InlineAlignment.Buttom; //
		private Text mText; //

		private static readonly string[] lienStrs = {
			"-","_"
		};
		private string mLineStr= lienStrs[1];                      //

		[SerializeField]
		private Text mLineText;
		public Text Text
		{
			get
			{
				if (mText == null)
				{
					mText = GetComponent<Text>();
				}
				return mText;
			}
		}
		public Text LineText
		{
			get
			{
				if (mLineText == null)
				{
					mLineText = CreateLineText();
				}
				return mLineText;
			}
		}

		public void SetLineAlignment(InlineAlignment v)
		{
			if (v == mLineAlignment)  return; 
			
			mLineAlignment = v;
			mLineStr = lienStrs[(int) v];
			RefreshInline();
		}

		public void RefreshInline()
		{
			var underline = LineText;
			underline.text = mLineStr;
			var perlineWidth = underline.preferredWidth;      //单个下划线宽度  



			var width = Text.preferredWidth;

			var lineCount = (int)Mathf.Round(width / perlineWidth);
			var str = new string(mLineStr[0],lineCount);
			underline.text = str;
			//Debug.LogFormat("generasTr:{0},count:{1}",str,lineCount);

		}

		public Text CreateLineText()
		{
			var underline = Instantiate(Text);
			underline.name = "Underline";


			underline.transform.SetParent(Text.transform);
			var rt = underline.rectTransform;


			//设置下划线坐标和位置  
			rt.anchoredPosition3D = Vector3.zero;
			rt.offsetMax = Vector2.zero;
			rt.offsetMin = Vector2.zero;
			rt.anchorMax = Vector2.one;
			rt.anchorMin = Vector2.zero;


			
			return underline;
		}
		protected override void Awake()
		{
			base.Awake();
			Text.RegisterDirtyLayoutCallback(OnDirtyLayoutCallback);
			SetLineAlignment(mLineAlignment);
		}

		protected override void OnEnable()
		{
			base.OnEnable();
			//Text.RegisterDirtyLayoutCallback(OnDirtyLayoutCallback);
		}

		protected override void OnDisable()
		{
			base.OnDisable();
			//Text.UnregisterDirtyLayoutCallback(OnDirtyLayoutCallback);

		}

		protected virtual void OnDirtyLayoutCallback()
		{
			RefreshInline();
		}

	}
}
